<?php
/**
 * Created by PhpStorm.
 * User: mengkang <i@mengkang.net>
 * Date: 2017/10/29 下午2:50
 */

define('ROOT', __DIR__);

$config = include ROOT."/config/provider.php";

define("SERVER_IP", $config['ip']);
define("SERVER_PORT", $config['port']);

$server = new \swoole_server(SERVER_IP, SERVER_PORT);

$server->addlistener(SERVER_IP,9602,SWOOLE_SOCK_TCP); // 用来监听 soa 配置中心的推送

$server->set(array(
    'worker_num'            => 1,
    'open_length_check'     => true,        // 开启协议解析
    'package_length_type'   => 'N',         // 长度字段的类型
    'package_length_offset' => 0,           // 第0个字节开始是包长度
    'package_body_offset'   => 4,           // 第4个字节开始计算长度
    'package_max_length'    => 2000000,     // 协议最大长度
));

$server->on('connect', function ($server, $fd) {
    echo "connection open: {$fd}\n";
});

$server->on('receive', "onReceive");

$server->start();


function onReceive($server, $fd, $from_id, $data) {
    $connection_info = $server->connection_info($fd, $from_id);
    if ($connection_info['server_port'] == SERVER_PORT) {
        RpcCall($server,$fd,$from_id,$data);
    }else{
        RpcNotice($server,$fd,$from_id,$data);
    }
}

function RpcCall($server, $fd, $from_id, $data){

}

/**
 * 控制中心的通知
 * @param $server
 * @param $fd
 * @param $from_id
 * @param $data
 */
function RpcNotice($server, $fd, $from_id, $data){
    $head = unpack('N', substr($data, 0 , 4)); // 获取包头
    $body = substr($data, 4);  // 获取数据
    $data = json_decode($body,true);

    if ($data['action'] == 'configUpdate'){
        include_once dirname(ROOT)."/Rpc/Dispatcher.php";
        Rpc\Dispatcher::configUpdate($data['data']);
    }

    $server->close($fd);
}